package com.wz.jiangsu.service.serviceImpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.wz.jiangsu.bean.entity.wazuh.WazuhSecurityEventSafetyDto;
import com.wz.jiangsu.bean.vo.resp.R;
import com.wz.jiangsu.mapper.WazuhMapper;
import com.wz.jiangsu.service.WazuhService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: wz
 * @author: wangzhou
 * @create: 2023-12-15 09:52
 * @description:
 **/
@Service
@Slf4j
public class WazuhServiceImpl implements WazuhService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private WazuhMapper wazuhMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public R<Map<Integer, WazuhSecurityEventSafetyDto>> getAllMapData() {

        Map<Integer, WazuhSecurityEventSafetyDto> wazuhDataMap = new HashMap<>();
        // 返回来的 key 为 String 类型，Object 为 LinkHashMap 类型
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(Map.class.getName());

        if (MapUtil.isNotEmpty(entries)) {
            Map<Integer, WazuhSecurityEventSafetyDto> finalWazuhDataMap = wazuhDataMap;
            entries.forEach((k, v) -> {
                Integer integerKey = Integer.valueOf(k.toString());
                WazuhSecurityEventSafetyDto dto = JSONUtil.toBean(JSONUtil.toJsonStr(v),WazuhSecurityEventSafetyDto.class);
                    finalWazuhDataMap.put(integerKey,dto);
            });
            return R.success(finalWazuhDataMap);
        }


        List<WazuhSecurityEventSafetyDto> wazuhDataList = wazuhMapper.getAllList();

        if (CollUtil.isEmpty(wazuhDataList)) {
            return R.error("查询出来的数据为空白的");
        }

        wazuhDataMap = wazuhDataList.stream().
                collect(
                        Collectors.toMap(WazuhSecurityEventSafetyDto::getWazuhRuleId, person -> person)
                );
        // wazuhDataMap 的类型进行变化，将 key 和 value 都变成 String 类型
        Map<String,String> mapString = new HashMap<>();
        wazuhDataMap.forEach((k,v)->{
            mapString.put(k.toString(), JSONUtil.toJsonStr(v));
        });
        redisTemplate.opsForHash().putAll(Map.class.getName(),mapString);

        return R.success(wazuhDataMap);
    }
}
